package com.whq.thrift.api.common.thriftclient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.constants.CommonErrorCodeConstants;
import com.whq.thrift.api.common.thriftserver.ResponseBase;

public abstract class AbstractApiJsonCallback extends AbstractBaseCallback {
	private static final Logger LOGGER = LoggerFactory.getLogger(AbstractApiJsonCallback.class);
	private static final Logger LOGGER_THRIFT_REQUEST_RESPONSE = LoggerFactory.getLogger(CommonConfigConstants.LOGGER_KEY_THRIFT_REQUEST_RESPONSE);
	
	private String fromMethod = "";
	
	private long startMs = 0l;
	private String method = "";
	private String flowId = "";
	
	@Override
	public void doResponse(String response, Exception exception) {
		String outString = response;
		if (exception != null) {
			if (exception instanceof java.util.concurrent.TimeoutException) {
				outString = JSON.toJSONString(new ResponseBase(CommonErrorCodeConstants.ERR_CODE_EXECUTE_TIMEOUT, "调用Thrift方法[" + method + "]超时"));;
			} else {
				LOGGER.error("调用Thrift方法[" + method + "]出错: ", exception);
				outString = JSON.toJSONString(new ResponseBase(CommonErrorCodeConstants.ERR_CODE_INVOKE_THRIFT_SERVICE_ERROR, "调用Thrift方法[" + method + "]出错"));
			}
		} 
		
		calcConsume(outString);
		doResponseApiJson(outString);
	}
	
	private void calcConsume(String response) {
		long timeConsumeMs = System.currentTimeMillis() - startMs;
		LOGGER_THRIFT_REQUEST_RESPONSE.info("invoke thrift service method[" + method + "], flowId[" + flowId + "], fromMethod[" + fromMethod + "], response[" + response + "], consume " + timeConsumeMs + " ms");
	}
	
	public void setStartMs(long startMs) {
		this.startMs = startMs;
	}
	
	public void setMethod(String method) {
		this.method = method;
	}
	
	public void setFlowId(String flowId) {
		this.flowId = flowId;
	}
	
	public void setFromMethod(String fromMethod) {
		this.fromMethod = fromMethod;
	}

	public abstract void doResponseApiJson(String response);

}
